

import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';

const ForgotPasswordPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 表单状态
  const [emailPhoneValue, setEmailPhoneValue] = useState('');
  const [verificationCodeValue, setVerificationCodeValue] = useState('');
  const [newPasswordValue, setNewPasswordValue] = useState('');
  const [confirmPasswordValue, setConfirmPasswordValue] = useState('');
  
  // 密码显示状态
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  // 验证码倒计时状态
  const [countdownSeconds, setCountdownSeconds] = useState(0);
  const [isGetCodeDisabled, setIsGetCodeDisabled] = useState(false);
  
  // 错误信息状态
  const [emailPhoneError, setEmailPhoneError] = useState('');
  const [verificationCodeError, setVerificationCodeError] = useState('');
  const [newPasswordError, setNewPasswordError] = useState('');
  const [confirmPasswordError, setConfirmPasswordError] = useState('');
  
  // 提交状态
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // 定时器引用
  const countdownTimerRef = useRef<number | null>(null);
  
  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '找回密码 - 学途';
    return () => {
      document.title = originalTitle;
    };
  }, []);
  
  // 清理定时器
  useEffect(() => {
    return () => {
      if (countdownTimerRef.current) {
        clearInterval(countdownTimerRef.current);
      }
    };
  }, []);
  
  // 验证邮箱或手机号
  const validateEmailOrPhone = (value: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^1[3-9]\d{9}$/;
    return emailRegex.test(value) || phoneRegex.test(value);
  };
  
  // 验证密码
  const validatePassword = (password: string): boolean => {
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/;
    return passwordRegex.test(password);
  };
  
  // 显示错误信息
  const showError = (setter: React.Dispatch<React.SetStateAction<string>>, message: string) => {
    setter(message);
  };
  
  // 隐藏错误信息
  const hideError = (setter: React.Dispatch<React.SetStateAction<string>>) => {
    setter('');
  };
  
  // 开始倒计时
  const startCountdown = () => {
    setCountdownSeconds(60);
    setIsGetCodeDisabled(true);
    
    countdownTimerRef.current = window.setInterval(() => {
      setCountdownSeconds(prevSeconds => {
        const newSeconds = prevSeconds - 1;
        if (newSeconds < 0) {
          setIsGetCodeDisabled(false);
          if (countdownTimerRef.current) {
            clearInterval(countdownTimerRef.current);
            countdownTimerRef.current = null;
          }
          return 0;
        }
        return newSeconds;
      });
    }, 1000);
  };
  
  // 获取验证码
  const handleGetVerificationCode = () => {
    const emailPhone = emailPhoneValue.trim();
    
    if (!emailPhone) {
      showError(setEmailPhoneError, '请输入邮箱或手机号');
      return;
    }
    
    if (!validateEmailOrPhone(emailPhone)) {
      showError(setEmailPhoneError, '请输入有效的邮箱或手机号');
      return;
    }
    
    hideError(setEmailPhoneError);
    startCountdown();
    
    // 模拟发送验证码
    console.log('发送验证码到:', emailPhone);
    showError(setVerificationCodeError, '');
  };
  
  // 验证表单
  const validateForm = (): boolean => {
    let isValid = true;
    
    // 验证邮箱/手机号
    const emailPhone = emailPhoneValue.trim();
    if (!emailPhone) {
      showError(setEmailPhoneError, '请输入邮箱或手机号');
      isValid = false;
    } else if (!validateEmailOrPhone(emailPhone)) {
      showError(setEmailPhoneError, '请输入有效的邮箱或手机号');
      isValid = false;
    } else {
      hideError(setEmailPhoneError);
    }
    
    // 验证验证码
    const verificationCode = verificationCodeValue.trim();
    if (!verificationCode) {
      showError(setVerificationCodeError, '请输入验证码');
      isValid = false;
    } else if (verificationCode.length !== 6) {
      showError(setVerificationCodeError, '验证码应为6位数字');
      isValid = false;
    } else {
      hideError(setVerificationCodeError);
    }
    
    // 验证新密码
    const newPassword = newPasswordValue;
    if (!newPassword) {
      showError(setNewPasswordError, '请输入新密码');
      isValid = false;
    } else if (!validatePassword(newPassword)) {
      showError(setNewPasswordError, '密码长度应为8-20位，包含字母和数字');
      isValid = false;
    } else {
      hideError(setNewPasswordError);
    }
    
    // 验证确认密码
    const confirmPassword = confirmPasswordValue;
    if (!confirmPassword) {
      showError(setConfirmPasswordError, '请确认新密码');
      isValid = false;
    } else if (newPassword !== confirmPassword) {
      showError(setConfirmPasswordError, '两次输入的密码不一致');
      isValid = false;
    } else {
      hideError(setConfirmPasswordError);
    }
    
    return isValid;
  };
  
  // 表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setIsSubmitting(true);
    
    // 模拟重置密码
    setTimeout(() => {
      navigate('/login');
    }, 2000);
  };
  
  // 邮箱/手机号失焦验证
  const handleEmailPhoneBlur = () => {
    const value = emailPhoneValue.trim();
    if (value && !validateEmailOrPhone(value)) {
      showError(setEmailPhoneError, '请输入有效的邮箱或手机号');
    } else {
      hideError(setEmailPhoneError);
    }
  };
  
  // 新密码失焦验证
  const handleNewPasswordBlur = () => {
    const value = newPasswordValue;
    if (value && !validatePassword(value)) {
      showError(setNewPasswordError, '密码长度应为8-20位，包含字母和数字');
    } else {
      hideError(setNewPasswordError);
    }
  };
  
  // 确认密码失焦验证
  const handleConfirmPasswordBlur = () => {
    const value = confirmPasswordValue;
    const newPassword = newPasswordValue;
    if (value && value !== newPassword) {
      showError(setConfirmPasswordError, '两次输入的密码不一致');
    } else {
      hideError(setConfirmPasswordError);
    }
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="bg-white shadow-sm border-b border-border-light fixed top-0 left-0 right-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            {/* Logo和网站名称 */}
            <div className="flex items-center space-x-3">
              <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
                <i className="fas fa-graduation-cap text-white text-lg"></i>
              </div>
              <span className="text-xl font-bold text-text-primary">学途</span>
            </div>
            
            {/* 主导航菜单 */}
            <nav className="hidden md:flex items-center space-x-8">
              <Link to="/home" className="text-text-secondary hover:text-primary py-1 transition-colors">首页</Link>
              <Link to="/course-list" className="text-text-secondary hover:text-primary py-1 transition-colors">课程中心</Link>
              <Link to="/about-us" className="text-text-secondary hover:text-primary py-1 transition-colors">关于我们</Link>
              <Link to="/help-center" className="text-text-secondary hover:text-primary py-1 transition-colors">帮助中心</Link>
            </nav>
            
            {/* 搜索框 */}
            <div className="hidden lg:flex items-center">
              <div className="relative">
                <input 
                  type="text" 
                  placeholder="搜索课程、讲师..." 
                  className="w-64 pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                />
                <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
              </div>
            </div>
            
            {/* 用户菜单 */}
            <div className="flex items-center space-x-4">
              <button className="relative p-2 text-text-secondary hover:text-primary transition-colors">
                <i className="fas fa-bell text-lg"></i>
                <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
              </button>
              
              {/* 未登录状态 */}
              <div className="flex items-center space-x-3">
                <Link to="/login" className="px-4 py-2 text-text-secondary hover:text-primary transition-colors">登录</Link>
                <Link to="/register" className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors">注册</Link>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* 主内容区域 */}
      <main className="pt-16 min-h-screen flex items-center justify-center py-12">
        <div className="max-w-md w-full px-4 sm:px-6 lg:px-8">
          {/* 找回密码表单 */}
          <div className="bg-white rounded-xl shadow-card p-8">
            {/* 页面标题 */}
            <div className="text-center mb-8">
              <div className="w-16 h-16 bg-primary bg-opacity-10 rounded-full flex items-center justify-center mx-auto mb-4">
                <i className="fas fa-key text-primary text-2xl"></i>
              </div>
              <h1 className="text-2xl font-bold text-text-primary mb-2">找回密码</h1>
              <p className="text-text-secondary">请输入您的注册邮箱或手机号，我们将发送验证码帮助您重置密码</p>
            </div>

            {/* 找回密码表单 */}
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* 邮箱/手机号输入 */}
              <div className="space-y-2">
                <label htmlFor="email-phone" className="block text-sm font-medium text-text-primary">注册邮箱/手机号 *</label>
                <input 
                  type="text" 
                  id="email-phone" 
                  name="email-phone" 
                  value={emailPhoneValue}
                  onChange={(e) => setEmailPhoneValue(e.target.value)}
                  onBlur={handleEmailPhoneBlur}
                  className={`w-full px-4 py-3 border border-border-light rounded-lg ${styles.formInputFocus}`}
                  placeholder="请输入邮箱或手机号" 
                  required 
                />
                {emailPhoneError && (
                  <div className={styles.errorMessage}>{emailPhoneError}</div>
                )}
              </div>

              {/* 验证码输入 */}
              <div className="space-y-2">
                <label htmlFor="verification-code" className="block text-sm font-medium text-text-primary">验证码 *</label>
                <div className="flex space-x-3">
                  <input 
                    type="text" 
                    id="verification-code" 
                    name="verification-code" 
                    value={verificationCodeValue}
                    onChange={(e) => setVerificationCodeValue(e.target.value)}
                    className={`flex-1 px-4 py-3 border border-border-light rounded-lg ${styles.formInputFocus}`}
                    placeholder="请输入验证码" 
                    maxLength={6} 
                    required 
                  />
                  <button 
                    type="button" 
                    onClick={handleGetVerificationCode}
                    disabled={isGetCodeDisabled}
                    className={`px-6 py-3 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors whitespace-nowrap ${isGetCodeDisabled ? styles.btnDisabled : ''}`}
                  >
                    {countdownSeconds > 0 ? `${countdownSeconds}秒后重试` : '获取验证码'}
                  </button>
                </div>
                {verificationCodeError && (
                  <div className={styles.errorMessage}>{verificationCodeError}</div>
                )}
              </div>

              {/* 新密码输入 */}
              <div className="space-y-2">
                <label htmlFor="new-password" className="block text-sm font-medium text-text-primary">新密码 *</label>
                <div className="relative">
                  <input 
                    type={showNewPassword ? 'text' : 'password'} 
                    id="new-password" 
                    name="new-password" 
                    value={newPasswordValue}
                    onChange={(e) => setNewPasswordValue(e.target.value)}
                    onBlur={handleNewPasswordBlur}
                    className={`w-full px-4 py-3 pr-12 border border-border-light rounded-lg ${styles.formInputFocus}`}
                    placeholder="请输入新密码（8-20位，包含字母和数字）" 
                    required 
                  />
                  <button 
                    type="button" 
                    onClick={() => setShowNewPassword(!showNewPassword)}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                  >
                    <i className={`fas ${showNewPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {newPasswordError && (
                  <div className={styles.errorMessage}>{newPasswordError}</div>
                )}
              </div>

              {/* 确认新密码输入 */}
              <div className="space-y-2">
                <label htmlFor="confirm-password" className="block text-sm font-medium text-text-primary">确认新密码 *</label>
                <div className="relative">
                  <input 
                    type={showConfirmPassword ? 'text' : 'password'} 
                    id="confirm-password" 
                    name="confirm-password" 
                    value={confirmPasswordValue}
                    onChange={(e) => setConfirmPasswordValue(e.target.value)}
                    onBlur={handleConfirmPasswordBlur}
                    className={`w-full px-4 py-3 pr-12 border border-border-light rounded-lg ${styles.formInputFocus}`}
                    placeholder="请再次输入新密码" 
                    required 
                  />
                  <button 
                    type="button" 
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                  >
                    <i className={`fas ${showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {confirmPasswordError && (
                  <div className={styles.errorMessage}>{confirmPasswordError}</div>
                )}
              </div>

              {/* 重置密码按钮 */}
              <button 
                type="submit" 
                disabled={isSubmitting}
                className="w-full py-3 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors font-medium"
              >
                {isSubmitting ? '重置中...' : '重置密码'}
              </button>

              {/* 返回登录链接 */}
              <div className="text-center">
                <Link to="/login" className="text-primary hover:text-blue-600 transition-colors">
                  <i className="fas fa-arrow-left mr-2"></i>返回登录
                </Link>
              </div>
            </form>
          </div>

          {/* 帮助信息 */}
          <div className="mt-8 text-center">
            <p className="text-text-secondary text-sm">
              遇到问题？请联系客服：
              <Link to="/help-center" className="text-primary hover:text-blue-600 transition-colors">帮助中心</Link>
            </p>
          </div>
        </div>
      </main>

      {/* 页脚 */}
      <footer className="bg-white border-t border-border-light py-12">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
              <h3 className="font-semibold text-text-primary mb-4">关于学途</h3>
              <ul className="space-y-2 text-text-secondary text-sm">
                <li><Link to="/about-us" className="hover:text-primary transition-colors">公司简介</Link></li>
                <li><a href="#" className="hover:text-primary transition-colors">联系我们</a></li>
                <li><a href="#" className="hover:text-primary transition-colors">招聘信息</a></li>
              </ul>
            </div>
            
            <div>
              <h3 className="font-semibold text-text-primary mb-4">帮助中心</h3>
              <ul className="space-y-2 text-text-secondary text-sm">
                <li><Link to="/help-center" className="hover:text-primary transition-colors">常见问题</Link></li>
                <li><a href="#" className="hover:text-primary transition-colors">使用指南</a></li>
                <li><a href="#" className="hover:text-primary transition-colors">意见反馈</a></li>
              </ul>
            </div>
            
            <div>
              <h3 className="font-semibold text-text-primary mb-4">法律条款</h3>
              <ul className="space-y-2 text-text-secondary text-sm">
                <li><Link to="/privacy-policy" className="hover:text-primary transition-colors">隐私政策</Link></li>
                <li><Link to="/user-agreement" className="hover:text-primary transition-colors">用户协议</Link></li>
                <li><a href="#" className="hover:text-primary transition-colors">版权声明</a></li>
              </ul>
            </div>
            
            <div>
              <h3 className="font-semibold text-text-primary mb-4">关注我们</h3>
              <div className="flex space-x-4">
                <a href="#" className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center text-text-secondary hover:bg-primary hover:text-white transition-colors">
                  <i className="fab fa-weixin"></i>
                </a>
                <a href="#" className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center text-text-secondary hover:bg-primary hover:text-white transition-colors">
                  <i className="fab fa-weibo"></i>
                </a>
                <a href="#" className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center text-text-secondary hover:bg-primary hover:text-white transition-colors">
                  <i className="fab fa-qq"></i>
                </a>
              </div>
            </div>
          </div>
          
          <div className="border-t border-border-light mt-8 pt-8 text-center text-text-secondary text-sm">
            <p>&copy; 2024 学途教育科技有限公司. 保留所有权利.</p>
          </div>
        </div>
      </footer>
    </div>
  );
};

export default ForgotPasswordPage;

